package dianmobile.eistarandroid.ui.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.okhttp.Request;

import java.util.List;
import java.util.Map;

import dianmobile.eistarandroid.ByhhAndroidApplication;
import dianmobile.eistarandroid.R;
import dianmobile.eistarandroid.background.GetMyActivityService;
import dianmobile.eistarandroid.network.request.LoginRequest;
import dianmobile.eistarandroid.network.request.RequestCallback;
import dianmobile.eistarandroid.usermanager.LoginManager;
import dianmobile.eistarandroid.utils.ConstantsData;
import dianmobile.eistarandroid.utils.InputValidator;
import im.fir.sdk.callback.VersionCheckCallback;
import im.fir.sdk.version.AppVersion;

public class LoginActivity extends Activity {

    private boolean isForceToWaitUserInput;
    protected EditText accountEdt;
    protected EditText passwordEdt;
    protected Button visitorLoginBtn;
    protected Button loginBtn;
    protected CheckBox rememberPasswordCk;
    protected CheckBox autoLoginCk;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        ByhhAndroidApplication application = (ByhhAndroidApplication)getApplication();
        List<Activity> activityList = application.getActivityList();
        for (Activity activity : activityList) {
            activity.finish();
        }
        application.getActivityList().add(this);

        Intent fromIntent = getIntent();
        isForceToWaitUserInput = fromIntent.getBooleanExtra("isForceToWaitUserInput", false);
        final LoginManager loginManager = ByhhAndroidApplication.acquire(this).getLoginManager();

        initView();

        //从账号管理界面启动login时传入账号密码登录
        String account = fromIntent.getStringExtra(ConstantsData.EXTRA_USER_NAME);
        String password = fromIntent.getStringExtra("password");
        if(account != null && !account.equals("")) {
            accountEdt.setText(account);
            passwordEdt.setText(password);
//            loginAsNormalUser();
        }
        if (loginManager.isAutoLogin()) {
            if (!isForceToWaitUserInput) {
                final ProgressDialog progressDialog = new ProgressDialog(this);
                progressDialog.setTitle("登陆中...");
                progressDialog.show();

            loginManager.doAutoLogin(new RequestCallback() {
                @Override
                public void onResult(Map<String, Object> result, String error) {
                    progressDialog.dismiss();
                    if (error == null) {
                        //启动后台服务，每30s请求一次动态
                        Intent serviceIntent = new Intent(LoginActivity.this, GetMyActivityService.class);
                        startService(serviceIntent);

                        ByhhAndroidApplication application = (ByhhAndroidApplication) LoginActivity.this.getApplication();
                        application.setLoginUserName(accountEdt.getText().toString());

                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        intent.putExtra("userName", accountEdt.getText().toString());
                        startActivity(intent);
                        finish();
                        loginManager.loginSuccess();
                    } else {
                        showLoginFailedDialog("网络异常");
                    }
                }
            });
            }
        }

    }

    @Override
    public void onDestroy(){
        ByhhAndroidApplication application = (ByhhAndroidApplication)getApplication();
        application.getActivityList().remove(this);
        super.onDestroy();
    }
    @Override
    public boolean onKeyDown(int key, KeyEvent event) {
        if (key == KeyEvent.KEYCODE_BACK) {
            ByhhAndroidApplication application = (ByhhAndroidApplication)getApplication();
            List<Activity> activityList = application.getActivityList();
            for (Activity activity : activityList) {
                activity.finish();
            }
            return true;
        } else {
            return super.onKeyDown(key, event);
        }
    }
    private void initView() {
        accountEdt = (EditText) findViewById(R.id.edt_account);
        passwordEdt = (EditText) findViewById(R.id.edt_password);
        rememberPasswordCk = (CheckBox) findViewById(R.id.ck_is_remenber_password);
        autoLoginCk = (CheckBox) findViewById(R.id.ck_is_auto_login);

        LoginManager loginManager = ByhhAndroidApplication.acquire(this).getLoginManager();
        boolean isSavedLoginData = loginManager.isHasSavedLoginData();
        boolean isAutoLogin = loginManager.isAutoLogin();
        rememberPasswordCk.setChecked(isSavedLoginData);
        autoLoginCk.setChecked(isAutoLogin);
        if (isSavedLoginData) {
            String savedAccount = loginManager.getSavedAccount();
            String savedPassword = loginManager.getSavedPassword();
            accountEdt.setText(savedAccount);
            passwordEdt.setText(savedPassword);
        }

        loginBtn = (Button) findViewById(R.id.btn_login);
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkUserInput()) {
                    loginAsNormalUser();
                }
            }
        });
        visitorLoginBtn = (Button) findViewById(R.id.btn_visitor);
        visitorLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginAsVisitor();
            }
        });
        autoLoginCk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (autoLoginCk.isChecked())
                    rememberPasswordCk.setChecked(true);
            }
        });
    }

    protected void showLoginFailedDialog(String hint) {
        LoginFailedDialog dialog = new LoginFailedDialog(this, LoginFailedDialog.DEFAULT_LAYOUT, hint);
        dialog.show();
    }

    protected void loginAsNormalUser() {

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("登录中...");
        progressDialog.show();

        LoginRequest.execute(getApplicationContext(),
                LoginRequest.createParams(accountEdt.getText().toString(), passwordEdt.getText().toString()),
                new RequestCallback() {
            @Override
            public void onResult(Map<String, Object> result, String error) {
                progressDialog.dismiss();
                if (error == null) {
                    if (!result.containsKey("error")) {
                        Toast.makeText(LoginActivity.this, "Login Success", Toast.LENGTH_SHORT).show();

                        ByhhAndroidApplication application = (ByhhAndroidApplication)LoginActivity.this.getApplication();
                        application.setLoginUserName(accountEdt.getText().toString());

                        dealViewAfterLoginSuccess();
                    }
                    else {
                        Toast.makeText(LoginActivity.this, (String)result.get("error"), Toast.LENGTH_SHORT).show();
                    }
                }
                else {
                    Toast.makeText(LoginActivity.this, "login error", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    protected void loginAsVisitor() {
        accountEdt.setText("guest");
        passwordEdt.setText("guest");
        loginAsNormalUser();
    }

    protected void dealViewAfterLoginSuccess() {
        if (!accountEdt.getText().toString().equals("guest")) {
            //启动后台服务，每30s请求一次动态
            Intent serviceIntent = new Intent(LoginActivity.this, GetMyActivityService.class);
            startService(serviceIntent);
            LoginManager loginManager = ByhhAndroidApplication.acquire(this).getLoginManager();
            loginManager.notifyLoginSetting(accountEdt.getText().toString(),
                    passwordEdt.getText().toString(),
                    rememberPasswordCk.isChecked(),
                    autoLoginCk.isChecked());
        }

        Intent gotoMainActivity = new Intent();
        gotoMainActivity.setClass(LoginActivity.this, MainActivity.class);
        gotoMainActivity.putExtra("userName", accountEdt.getText().toString());
        startActivity(gotoMainActivity);
        finish();
    }

    protected boolean checkUserInput() {
        String checkAccount = InputValidator.checkAccountInput(accountEdt.getText().toString());
        if (checkAccount != null) {
            showLoginFailedDialog(checkAccount);
            return false;
        }

        String checkPassword = InputValidator.checkPasswordInput(passwordEdt.getText().toString());
        if (checkPassword != null) {
            showLoginFailedDialog(checkPassword);
            return false;
        }

        return true;    // inputs are OK
    }
}

class LoginFailedDialog extends Dialog{

    public static final int DEFAULT_LAYOUT = R.layout.dialog_login_failed;
    private int layout;
    private String hint;
    private Button confirmBtn;
    private TextView hintTv;

    public LoginFailedDialog(Context context, int layout, String hint) {
        super(context, R.style.nonTitleDialog);
        this.layout = layout;
        this.hint = hint;

        /*
         * if the param of this method is true, user can not touch
         * outside space of dialog to dismiss this dialog.
         */
        setCanceledOnTouchOutside(false);

        setTitle("登录失败");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(layout);

        hintTv = (TextView) findViewById(R.id.tv_hint);
        hintTv.setText(hint);

        confirmBtn = (Button) findViewById(R.id.btn_confirm);
        confirmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismissDialog();
            }
        });
    }
    private void dismissDialog() {dismiss();}
}

/**
 * 检查版本 并更新
 */
class MyVersionCheckCallBack extends VersionCheckCallback {

    private Context context;
    public MyVersionCheckCallBack(Context context) {
        this.context = context;
    }
    @Override
    public void onSuccess(final AppVersion appVersionMsg, boolean shouldUpdate) {
        Log.d("checkVersion", "appVersion: " + appVersionMsg + " boolean: " + shouldUpdate);
        if (shouldUpdate) {
            String localAppVersionName = "";
            PackageManager packageManager = context.getPackageManager();
            try {
                PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
                localAppVersionName = packageInfo.versionName;
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("发现新版本 是否更新？");
            builder.setMessage("当前版本："+localAppVersionName+"\n最新版本：" + appVersionMsg.getVersionName() + "\n更新日志：" + appVersionMsg.getChangeLog());
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    String updateUrl = appVersionMsg.getUpdateUrl();
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    intent.setData(Uri.parse(updateUrl));
                    context.startActivity(intent);
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.create().show();
        }
    }

    @Override
    public void onFail(Request failMsg, Exception e) {
        Log.d("checkVersion", "fail: " +failMsg + " exception: " +e);
    }

    @Override
    public void onStart() {
        Log.d("checkVersion", "onStart");
    }

    @Override
    public void onFinish() {
        Log.d("checkVersion", "onFinish");
    }
}